<?php
class model_link_item extends common_model {
	/**
	 * 基本表属性
	 */
	protected $table = 'link_item';
	protected $pk = 'link_item_id';
	
	/**
	 * 添加
	 * @param array $data 数据
	 */
	public function add($data) {
		// 添加数据
		$link_item_id = $this->create($data);
		// 添加sequence
		$this->update(array('link_item_id' => $link_item_id, 'sequence' => $link_item_id));
		
		return $link_item_id;
	}
	
	/**
	 * 获取所有数据
	 */
	public function get_tree() {
		// 链接
		$item_res = $this->find_all('deleted=0', 'sequence ASC');
		
		// 分类
		$link_category = new model_link_category();
		$cat_res = $link_category->find_all(1, 'sequence ASC');
		$cat_res_byid = array();
		foreach ($cat_res as $row) {
			$cat_res_byid[$row['link_cat_id']]['info'] = $row;
			$cat_res_byid[$row['link_cat_id']]['data'] = array();
		}
		
		// 链接绑定到分类或父链接
		foreach ($item_res as $row) {
			if($row['parent_id'] == 0) {
				isset($cat_res_byid[$row['link_cat_id']]['data'][$row['link_item_id']]['children']) && $row['children'] = $cat_res_byid[$row['link_cat_id']]['data'][$row['link_item_id']]['children'];
				$cat_res_byid[$row['link_cat_id']]['data'][$row['link_item_id']] = $row;		
			} else {
				$cat_res_byid[$row['link_cat_id']]['data'][$row['parent_id']]['children'][$row['link_item_id']] = $row;
			}
		}

		// 整合数据
		$cats = array();
		foreach ($cat_res_byid as $row) {
			if($row['info']['parent_id'] == 0) {
				$cats[$row['info']['link_cat_id']] = $row;
			} else {
				$cats[$row['info']['parent_id']]['data'][$row['info']['link_cat_id']] = $row;
			}
		}
		return $cats;
	}
}
